import { getSystemLanguage, LanguageLocale, lngKey } from '@/utils/localize/i18next';
import eventEmitter from '@/utils/eventManager';
import { pxToVh, pxToVw, screenHeight } from '@/utils/pxToVx';
import { FlashList } from '@shopify/flash-list';
import React, { useEffect, useRef, useState } from 'react';
import { Pressable, StyleSheet, Text, TextInput, View, Keyboard, Platform, ScrollView } from 'react-native';
import BottomDrawer, { BottomDrawerMethods } from 'react-native-animated-bottom-drawer';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { getStorageItem } from '@/utils/storage';
import IconArrow from './svg/icon_arrow.svg';
import IconCheck from './svg/icon_check.svg';
import IconSearch from './svg/icon_search.svg';
import { useDispatch, useSelector } from 'react-redux';
import { t } from 'i18next';
import { RootState } from '@/store/store';
import { setVisible } from '@/stores/slice/changeLanguageSlice';
import { CustomerText } from '@/components/CustomerText/customerText';
const language_list = require('./language_locale_list'); // 导入语言列表

interface IProps {
  // 将选择的item抛出
  callback?: (item: LanguageLocale) => void;
}

export const ChangeLanguage: React.FC<IProps> = ({ callback }) => {
  const drawerRef = useRef<BottomDrawerMethods>(null);
  const insets = useSafeAreaInsets();
  const [searchValue, setSearchText] = useState('');
  const [selectedOption, setSelectedOption] = useState('');
  const [moreLanguage, setMoreLanguage] = useState<LanguageLocale[]>(language_list);
  const visible = useSelector((state: RootState) => state.changeLanguage.visible);
  const [isEn, setIsEn] = useState(true);
  const throttleRef = useRef(false);
  const dispatch = useDispatch();
  const [keyboardVisible, setKeyboardVisible] = useState(false);
  const searchInputRef = useRef<TextInput>(null);

  // 监听键盘显示/隐藏
  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
      setKeyboardVisible(true);
    });
    const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
      setKeyboardVisible(false);
    });

    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  useEffect(() => {
    if (visible) {
      drawerRef.current?.open();

      // 获取上次选择的语言，如果没有，则获取系统语言
      const lng = getStorageItem(lngKey) ?? getSystemLanguage();
      let isEn = true;
      if (lng.includes('zh')) {
        isEn = false;
      }
      setIsEn(isEn);

      setMoreLanguage(
        language_list.sort((item: any, item2: any) => {
          const a = isEn ? item.language_en : item.language_zh;
          const b = isEn ? item2.language_en : item2.language_zh;
          return a > b ? 1 : -1;
        }),
      );
    }
  }, [visible]);

  const handleSearchChange = (text: string) => {
    setSearchText(text);

    setMoreLanguage(
      language_list
        .filter((item: any) =>
          (isEn ? item.language_en : item.language_zh).toLocaleLowerCase().includes(text.toLocaleLowerCase()),
        )
        .sort((item: any, item2: any) => {
          const a = isEn ? item.language_en : item.language_zh;
          const b = isEn ? item2.language_en : item2.language_zh;
          return a > b ? 1 : -1;
        }),
    );
  };

  const handleSelectedOption = (item: any) => {
    console.log('====================================');
    console.log(item);
    console.log('====================================');

    if (throttleRef.current) {
      return;
    }
    throttleRef.current = true;

    setSelectedOption(isEn ? item.language_en : item.language_zh);

    drawerRef.current?.close();

    const remove = setTimeout(() => {
      if (callback) {
        callback(item);
      }
      clearTimeout(remove);
    }, 500);
  };

  const _renderItem = ({ item }: any) => {
    return (
      <Pressable style={styles.language_item_container} onPress={() => handleSelectedOption(item)}>
        <Text style={styles.language_item}>{isEn ? item.language_en : item.language_zh}</Text>
        {(isEn ? item.language_en : item.language_zh) === selectedOption && (
          <View style={styles.language_item_check}>
            <IconCheck />
          </View>
        )}
      </Pressable>
    );
  };

  const onClose = () => {
    const timeout = setTimeout(() => {
      dispatch(setVisible(false));
      clearTimeout(timeout);
    }, 500);
  };

  const itemSeparator = () => <View style={styles.separator} />;

  // 根据键盘状态调整抽屉高度
  const drawerHeight =
    keyboardVisible && Platform.OS === 'android'
      ? screenHeight * 0.5 // 键盘显示时，抽屉高度减小
      : screenHeight - insets.top - 10;

  return (
    <>
      <BottomDrawer
        ref={drawerRef}
        initialHeight={screenHeight - insets.top - 10}
        customStyles={{
          handleContainer: styles.drawer_handle,
          handle: styles.drawer_handle_icon,
          container:
            keyboardVisible && Platform.OS === 'android'
              ? { height: drawerHeight, position: 'absolute', top: 0 }
              : undefined,
        }}
        onClose={onClose}
      >
        <ScrollView
          style={styles.drawer_wrapper}
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{ flexGrow: 1 }}
        >
          <View style={styles.drawer_header_wrapper}>
            <Pressable
              style={styles.drawer_header_icon}
              onPress={() => {
                Keyboard.dismiss();
                drawerRef.current?.close();
              }}
            >
              <IconArrow />
            </Pressable>
            <View style={styles.drawer_header}>
              <CustomerText style={styles.drawer_header_text}>More</CustomerText>
            </View>
          </View>

          <View style={styles.drawer_search_wrapper}>
            <IconSearch />
            <TextInput
              ref={searchInputRef}
              textAlignVertical="top"
              style={styles.drawer_search}
              placeholder={t('Search')}
              placeholderTextColor={'gray'}
              value={searchValue}
              onChangeText={handleSearchChange}
              onSubmitEditing={() => Keyboard.dismiss()}
              onFocus={() => {
                // 在Android上，当输入框获得焦点时，确保输入框可见
                if (Platform.OS === 'android') {
                  setTimeout(() => {
                    // 确保输入框在可见区域
                    searchInputRef.current?.measureInWindow((x, y, width, height) => {
                      if (y < 0) {
                        // 如果输入框在屏幕外，滚动到可见区域
                        drawerRef.current?.open();
                      }
                    });
                  }, 300);
                }
              }}
            />
          </View>
          <View style={styles.language}>
            <FlashList
              data={moreLanguage}
              estimatedItemSize={100}
              extraData={[selectedOption, keyboardVisible]}
              renderItem={_renderItem}
              ItemSeparatorComponent={itemSeparator}
              ListFooterComponentStyle={{ paddingBottom: insets.bottom + 60 }}
              showsVerticalScrollIndicator={false}
              onScrollBeginDrag={() => Keyboard.dismiss()}
              keyboardShouldPersistTaps="handled"
            />
          </View>
        </ScrollView>
      </BottomDrawer>
    </>
  );
};

const styles = StyleSheet.create({
  drawer_handle: {
    height: pxToVh(20),
  },
  drawer_handle_icon: {
    display: 'none',
  },
  drawer_wrapper: {
    flex: 1,
  },
  drawer_header_wrapper: {
    height: pxToVh(62),
    position: 'relative',
    flexDirection: 'row',
    paddingHorizontal: pxToVw(20),
  },
  drawer_header_icon: {
    position: 'absolute',
    left: pxToVw(20),
    top: pxToVh(-8),
  },
  drawer_header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    zIndex: -1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  drawer_header_text: {
    fontSize: pxToVh(17),
    lineHeight: pxToVh(22),
    fontWeight: '600',
    color: '#000',
  },
  drawer_search_wrapper: {
    marginHorizontal: pxToVw(20),
    paddingHorizontal: pxToVw(12),
    height: pxToVh(44),
    flexDirection: 'row',
    borderRadius: pxToVw(8),
    backgroundColor: 'rgba(244, 244, 244, 1)',
    columnGap: pxToVh(8),
    alignItems: 'center',
  },
  drawer_search: {
    width: '100%',
    color: 'rgba(0, 0, 0, 1)',
  },
  language: {
    flex: 1,
    paddingHorizontal: pxToVw(20),
    marginTop: pxToVh(28),
  },
  language_item_container: {
    width: '100%',
    height: pxToVh(32),
    paddingBottom: pxToVh(12),
    borderBottomWidth: pxToVh(0.5),
    borderColor: 'rgba(0, 0, 0, 0.1)',
    position: 'relative',
  },
  language_item: {
    textAlign: 'center',
    color: 'rgba(0, 0, 0, 1)',
  },
  language_item_check: {
    position: 'absolute',
    right: 0,
    top: 0,
  },
  separator: {
    height: pxToVh(16),
    width: '100%',
  },
});
